package com.foohoo.benchmark.jvm;

import org.openjdk.jmh.annotations.*;
import org.openjdk.jmh.infra.Blackhole;

import java.util.concurrent.TimeUnit;

/**
 * 测试即时编译器编译优化(方法内联)对性能的提升
 * Benchmark                           Mode  Cnt  Score   Error  Units
 * JustInTimeWithInline.withInline     avgt    3  3.283 ± 1.037  ns/op
 * JustInTimeWithInline.withoutInline  avgt    3  5.357 ± 6.131  ns/op
 * 一句话结论: 被判定为热点代码后，即时编译器(jit)会通过多种手段对代码进行优化，可以显著提升性能
 *
 * @author mzdbxqh
 * @date 2020-10-22 13:45
 **/
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
@Warmup(iterations = 3, time = 1)
@Measurement(iterations = 3, time = 1)
@Fork(1)
@Threads(1)
@State(Scope.Benchmark)
public class JustInTimeWithInline {

	private int plus(int x, int y) {
		return x + y;
	}

	@Benchmark
	@CompilerControl(CompilerControl.Mode.INLINE)
	public void withInline(Blackhole bh) {
		int x = 1, y = 2;
		int result = plus(x, y);
		bh.consume(result);
	}

	@Benchmark
	@CompilerControl(CompilerControl.Mode.DONT_INLINE)
	public void withoutInline(Blackhole bh) {
		int x = 1, y = 2;
		int result = plus(x, y);
		bh.consume(result);
	}
}
